package com.lzp.java.concurrent.deadlock;

import com.lzp.mybatis.dataobject.Account;

import java.util.concurrent.TimeUnit;

/**
 * 互相转账死锁
 *
 * @author lzp
 * @date 2020/03/04
 */
public class TransferMoneyDeadLock implements Runnable {
    private int flag;

    public TransferMoneyDeadLock(int flag) {
        this.flag = flag;
    }

    private static Account account1 = new Account(500);
    private static Account account2 = new Account(500);

    public static void main(String[] args) throws InterruptedException {
        Thread thread0 = new Thread(new TransferMoneyDeadLock(0));
        Thread thread1 = new Thread(new TransferMoneyDeadLock(1));
        thread0.start();
        thread1.start();
        thread0.join();
        thread1.join();
        System.out.println("账户1余额：" + account1.blance);
        System.out.println("账户2余额：" + account2.blance);
    }

    @Override
    public void run() {
        if (flag == 0) {
            transMoney(account1, account2, 200);
        } else {
            transMoney(account2, account1, 200);
        }
    }

    private void transMoney(Account from, Account to, int account) {
        synchronized (from) {
            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (to) {
                if (from.blance < account) {
                    throw new RuntimeException("账户余额不足");
                }
                from.blance -= account;
                to.blance += account;
                System.out.println("成功转账" + account + "元");
            }
        }
    }

    static class Account {
        int blance;

        public Account(int blance) {
            this.blance = blance;
        }
    }
}
